<template>
  <view class="password-container">
    <view class="page-header">
      <view class="header-title">{{ isSetPassword ? '设置密码' : '修改密码' }}</view>
      <view class="header-subtitle">{{ isSetPassword ? '为您的账号设置登录密码' : '修改您的登录密码' }}</view>
    </view>

    <form @submit="handleSubmit">
      <!-- 旧密码（仅修改密码时显示） -->
      <view v-if="!isSetPassword" class="form-item">
        <text class="form-label">当前密码</text>
        <view class="input-wrapper">
          <input
            class="form-input"
            :type="showOldPassword ? 'text' : 'password'"
            v-model="oldPassword"
            placeholder="请输入当前密码"
            maxlength="20"
          />
          <view class="password-toggle" @click="toggleOldPassword">
            <text class="toggle-icon">{{ showOldPassword ? '👁' : '🙈' }}</text>
          </view>
        </view>
      </view>

      <!-- 新密码 -->
      <view class="form-item">
        <text class="form-label">{{ isSetPassword ? '设置密码' : '新密码' }}</text>
        <view class="input-wrapper">
          <input
            class="form-input"
            :type="showNewPassword ? 'text' : 'password'"
            v-model="newPassword"
            placeholder="请输入6-20位密码"
            maxlength="20"
          />
          <view class="password-toggle" @click="toggleNewPassword">
            <text class="toggle-icon">{{ showNewPassword ? '👁' : '🙈' }}</text>
          </view>
        </view>
      </view>

      <!-- 确认密码 -->
      <view class="form-item">
        <text class="form-label">确认密码</text>
        <view class="input-wrapper">
          <input
            class="form-input"
            :type="showConfirmPassword ? 'text' : 'password'"
            v-model="confirmPassword"
            placeholder="请再次输入密码"
            maxlength="20"
          />
          <view class="password-toggle" @click="toggleConfirmPassword">
            <text class="toggle-icon">{{ showConfirmPassword ? '👁' : '🙈' }}</text>
          </view>
        </view>
      </view>

      <!-- 密码强度提示 -->
      <view class="password-tips">
        <text class="tips-title">密码要求：</text>
        <text class="tips-item" :class="{ 'valid': passwordValidation.length }">• 长度6-20位</text>
        <text class="tips-item" :class="{ 'valid': passwordValidation.hasLetter }">• 包含字母</text>
        <text class="tips-item" :class="{ 'valid': passwordValidation.hasNumber }">• 包含数字</text>
      </view>

      <!-- 提交按钮 -->
      <button class="submit-btn" form-type="submit" :disabled="isSubmitting">
        {{ isSubmitting ? '处理中...' : (isSetPassword ? '设置密码' : '修改密码') }}
      </button>
    </form>

    <!-- 短信验证码设置密码（备用方案） -->
    <view v-if="isSetPassword" class="alternative-method">
      <text class="alternative-text">也可以通过短信验证码设置密码</text>
      <text class="alternative-link" @click="useSmsVerification">使用短信验证</text>
    </view>

    <!-- 忘记密码提示 -->
    <view v-if="!isSetPassword" class="forgot-password">
      <text class="forgot-text">忘记密码？</text>
      <text class="forgot-link" @click="resetPassword">重置密码</text>
    </view>
  </view>
</template>

<script>
import { userApi } from '../../api'
import { getCode } from '../../api/user.js'

export default {
  data() {
    return {
      isSetPassword: false, // 是否为设置密码（true）还是修改密码（false）
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
      showOldPassword: false,
      showNewPassword: false,
      showConfirmPassword: false,
      isSubmitting: false,
      
      // 短信验证相关
      useSms: false,
      phone: '',
      code: '',
      countdown: 0,
      timer: null
    }
  },
  
  computed: {
    // 密码验证
    passwordValidation() {
      return {
        length: this.newPassword.length >= 6 && this.newPassword.length <= 20,
        hasLetter: /[a-zA-Z]/.test(this.newPassword),
        hasNumber: /\d/.test(this.newPassword)
      }
    },
    
    // 密码强度
    passwordStrength() {
      const validCount = Object.values(this.passwordValidation).filter(Boolean).length
      if (validCount === 0) return 'none'
      if (validCount === 1) return 'weak'
      if (validCount === 2) return 'medium'
      return 'strong'
    }
  },
  
  onLoad(options) {
    // 根据传入的参数判断是设置密码还是修改密码
    this.isSetPassword = options.action === 'set'
    
    // 获取用户手机号（用于短信验证）
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo && userInfo.phone) {
      this.phone = userInfo.phone
    }
  },
  
  methods: {
    // 切换旧密码显示状态
    toggleOldPassword() {
      this.showOldPassword = !this.showOldPassword
    },
    
    // 切换新密码显示状态
    toggleNewPassword() {
      this.showNewPassword = !this.showNewPassword
    },
    
    // 切换确认密码显示状态
    toggleConfirmPassword() {
      this.showConfirmPassword = !this.showConfirmPassword
    },
    
    // 验证密码格式
    validatePassword(password) {
      if (!password || password.length < 6 || password.length > 20) {
        return '密码长度必须为6-20位'
      }
      if (!/[a-zA-Z]/.test(password)) {
        return '密码必须包含字母'
      }
      if (!/\d/.test(password)) {
        return '密码必须包含数字'
      }
      return null
    },
    
    // 表单验证
    validateForm() {
      // 验证旧密码（仅修改密码时）
      if (!this.isSetPassword && !this.oldPassword) {
        uni.showToast({
          title: '请输入当前密码',
          icon: 'none'
        })
        return false
      }
      
      // 验证新密码
      const passwordError = this.validatePassword(this.newPassword)
      if (passwordError) {
        uni.showToast({
          title: passwordError,
          icon: 'none'
        })
        return false
      }
      
      // 验证确认密码
      if (this.newPassword !== this.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    // 提交表单
    async handleSubmit() {
      if (this.isSubmitting) return
      
      if (!this.validateForm()) return
      
      try {
        this.isSubmitting = true
        
        uni.showLoading({
          title: this.isSetPassword ? '设置中...' : '修改中...'
        })
        
        // 获取用户信息
        const userInfo = uni.getStorageSync('userInfo')
        if (!userInfo || !userInfo.id) {
          uni.showToast({
            title: '用户信息获取失败',
            icon: 'none'
          })
          return
        }

        const requestData = {
          userId: userInfo.id,
          phone: userInfo.phone,
          newPassword: this.newPassword
        }

        // 如果是修改密码，需要提供旧密码
        if (!this.isSetPassword) {
          requestData.oldPassword = this.oldPassword
        }
        
        // 调用API
        const res = await userApi.changePassword(requestData)
        
        if (res && res.code === 200) {
          uni.showToast({
            title: this.isSetPassword ? '密码设置成功' : '密码修改成功',
            icon: 'success'
          })
          
          // 更新本地用户信息，标记已设置密码
          const userInfo = uni.getStorageSync('userInfo')
          if (userInfo) {
            userInfo.hasPassword = true
            uni.setStorageSync('userInfo', userInfo)
          }
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(res?.message || '操作失败')
        }
        
      } catch (error) {
        console.error('密码操作失败:', error)
        uni.showToast({
          title: error.message || '操作失败，请重试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
        this.isSubmitting = false
      }
    },
    
    // 使用短信验证设置密码
    useSmsVerification() {
      uni.showModal({
        title: '提示',
        content: '将通过短信验证码来设置密码，是否继续？',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/password/sms-set'
            })
          }
        }
      })
    },

    // 重置密码
    resetPassword() {
      uni.showModal({
        title: '重置密码',
        content: '将通过短信验证码重置您的密码，是否继续？',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/password/sms-set?type=reset'
            })
          }
        }
      })
    }
  },
  
  // 组件销毁时清除定时器
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style>
.password-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 0 30rpx;
}

.page-header {
  padding: 60rpx 0 40rpx;
  text-align: center;
}

.header-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.header-subtitle {
  font-size: 28rpx;
  color: #666;
}

.form-item {
  background-color: #fff;
  margin-bottom: 30rpx;
  border-radius: 20rpx;
  padding: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.form-input {
  flex: 1;
  height: 80rpx;
  padding: 0 80rpx 0 20rpx;
  border: 1px solid #eee;
  border-radius: 40rpx;
  font-size: 28rpx;
  background-color: #f8f8f8;
}

.password-toggle {
  position: absolute;
  right: 20rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.toggle-icon {
  font-size: 32rpx;
}

.password-tips {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 20rpx;
  margin-bottom: 40rpx;
}

.tips-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  display: block;
  margin-bottom: 20rpx;
}

.tips-item {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
  transition: color 0.3s;
}

.tips-item.valid {
  color: #4080FF;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #4080FF;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  margin-bottom: 40rpx;
}

.submit-btn:disabled {
  background-color: #ccc;
}

.alternative-method {
  text-align: center;
  padding: 40rpx 0;
}

.alternative-text {
  font-size: 24rpx;
  color: #999;
  margin-right: 20rpx;
}

.alternative-link {
  font-size: 24rpx;
  color: #4080FF;
  text-decoration: underline;
}

.forgot-password {
  text-align: center;
  padding: 20rpx 0;
}

.forgot-text {
  font-size: 24rpx;
  color: #999;
  margin-right: 20rpx;
}

.forgot-link {
  font-size: 24rpx;
  color: #4080FF;
  text-decoration: underline;
}
</style>
